﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using QxFramework.Core;
using UnityEngine.Assertions;
using GameControl;
using UnityEngine.UI;
using System;
using System.Reflection;
using GameMap;

public class ParamPanel : UIBase
{
    ItemField editingItem;
    List<FuncField> funcs;
    List<GameObject> funcsPanel;
    int enablePanelCnt;
    List<GameObject> propertyPanel;
    int enablePropertyPanelCnt;
    GameObject funcContent;
    bool hasInit = false;
    private void Awake()
    {
        funcsPanel = new List<GameObject>();
        funcs = new List<FuncField>();
        propertyPanel = new List<GameObject>();
        transform.Find("TransformButton").Find("Flip").GetComponent<Button>().onClick.SetListener(Flip);
        transform.Find("TransformButton").Find("Rotate").GetComponent<Button>().onClick.SetListener(Rotate);
        transform.Find("TransformButton").Find("Delete").GetComponent<Button>().onClick.SetListener(Delete);

        Init(null);

    }

    void Flip()
    {
        if (editingItem == null)
        {
            return;
        }
        var r = (editingItem as CombinableItemField).MeshTransform;
        int intMeshRotate = (editingItem as CombinableItemField).MeshTransform.MeshRotate ;
        if (intMeshRotate % 2 == 0)
        {
            r.IsFlipedInMesh ^= true;
        }
        else
        {
            r.IsFlipedInMesh ^= true;
            intMeshRotate += 2;
            if (intMeshRotate >= 4)intMeshRotate -= 4;
        }
        r.MeshRotate = intMeshRotate ;
        MessageManager.Instance.Get<ItemMapEvent>().DispatchMessage(ItemMapEvent.ChangeTransform, this, new ItemMapArgs
        {
            User=CombineUI.Instance.UserName,
            ItemName = editingItem.ItemName,
            MeshTransform = r

        });
        AudioControl.Instance.PlaySound("Mouse");
    }
    void Rotate()
    {
        if (editingItem == null)
        {
            return;
        }
        var r = (editingItem as CombinableItemField).MeshTransform;
        /*  if (editingItem.MeshTransform.IsFliped)
          {
              r.MeshRotate -= 1;
          }else*/
        {
            r.MeshRotate += 1;
        }
        if (r.MeshRotate < 0) r.MeshRotate += 4;
        MessageManager.Instance.Get<ItemMapEvent>().DispatchMessage(ItemMapEvent.ChangeTransform, this, new ItemMapArgs
        {
            User = CombineUI.Instance.UserName,
            ItemName = editingItem.ItemName,
            MeshTransform = r

        });
        AudioControl.Instance.PlaySound("Mouse");
    }
    void Delete()
    {
        if (editingItem == null)
        {
            return;
        }
        UIManager.Instance.Open("DialogWindowUI", 5, args: new DialogWindowUI.DialogWindowUIArg
        ("注意", "确定要删除物体吗", null, "确定","取消", () => {

            MessageManager.Instance.Get<ItemMapEvent>().DispatchMessage(ItemMapEvent.DeleteInBench, this, new ItemMapArgs
            {
                ItemName = editingItem.ItemName
            });

        }));
        AudioControl.Instance.PlaySound("Mouse");
    }
   

    public void Init(object args)
    {
        MessageManager.Instance.Get<ItemFuncEvent>().RegisterHandler(ItemFuncEvent.DoneChangeKey, (object sender,EventArgs e) => {
            RefreshFuncs();
            return null;
        });
        if(args == null)
        {
          //  this.gameObject.SetActive(false);
         //   return;
        }
        else
        {
            this.gameObject.SetActive(true);
        }
   //     Debug.Assert(args is ItemField);
        editingItem = args as ItemField;
        if (editingItem == null)
        {
            funcs = new List<FuncField>();
        }
        else
        {
            funcs = GameManager.Get<IItemFuncManager>().GetFuncFieldAbout(editingItem.ItemName);

        }
        funcContent = transform.Find("Frame").Find("Functions").gameObject.GetComponentInChildren<ScrollRect>().content.gameObject;
        //      Debug.Log(funcsPanel);

        if (!hasInit)
        {
            funcsPanel = new List<GameObject>();
            funcsPanel.Add(funcContent.transform.GetChild(0).gameObject);
            propertyPanel = new List<GameObject>();
            propertyPanel.Add(transform.Find("PropertySetting(0)").Find("PropertySetting").
                GetComponentInChildren<ScrollRect>().content.transform.GetChild(0).gameObject);
            hasInit = true;
        }

        RefreshFuncs();
        RefreshNameAndAbstract();
        RefreshPropertySetting();
    }

    void DisableAllInPanel(ref List<GameObject>panel,ref int cnt)
    {
        foreach (var x in panel)
        {
            x.SetActive(false);
        }
        cnt = 0;
    }
    GameObject GetNewPanel(ref List<GameObject>list,ref int cnt)
    {
        if (cnt== list.Count)
        {
            list.Add(GameObject.Instantiate(list[0], list[0].transform.parent));
        }
        list[cnt].SetActive(true);
        return list[cnt++];
    }

    void RefreshPropertySetting()
    {
        DisableAllInPanel(ref propertyPanel, ref enablePropertyPanelCnt);
        if (editingItem == null)
        {
            return;
        }
        var fields = editingItem.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
        foreach (var x in fields)
        {
            if (!x.IsDefined(typeof(HeaderAttribute))) continue;
            var a = x.GetCustomAttribute<HeaderAttribute>(true);//GetAttribute<Bind>(true);
            try
            {
                var tp = a.GetType().GetField("header");
                var e = (string)tp.GetValue(a);
            //    x.GetValue(editingItem);
                GetNewPanel(ref propertyPanel,ref enablePropertyPanelCnt).GetComponentInChildren<Text>().text = "     "+e + " ---- " + x.GetValue(editingItem);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
    }
    void RefreshNameAndAbstract()
    {
        if (editingItem == null)
        {
            this.transform.Find("Name").GetComponentInChildren<Text>().text = "";
            this.transform.Find("Abstract(0)").Find("Abstract").GetComponentInChildren<Text>().text = "";
        }
        else
        {

            this.transform.Find("Name").GetComponentInChildren<Text>().text = editingItem.ItemName.Split('_')[0];
            this.transform.Find("Abstract(0)").Find("Abstract").GetComponentInChildren<Text>().text = GameManager.Get<IItemInstantiateManager>().GetItemSettingByName(editingItem.ItemName).Abstract;
        }
    }
    void RefreshFuncs()
    {
        DisableAllInPanel(ref funcsPanel,ref enablePanelCnt);
        if (editingItem == null)
        {
            return;
        }
        funcs = GameManager.Get<IItemFuncManager>().GetFuncFieldAbout(editingItem.ItemName);
        foreach (var x in funcs)
        {
            GameObject p = GetNewPanel(ref funcsPanel,ref enablePanelCnt);
            p.transform.Find("Image").GetComponent<Image>().sprite = GameManager.Get<IItemFuncManager>().GetFuncSettingAbout(x).FuncIcon;
            p.transform.Find("Image").GetComponent<Label>().Content = GameManager.Get<IItemFuncManager>().GetFuncSettingAbout(x).Name+": "+ GameManager.Get<IItemFuncManager>().GetFuncSettingAbout(x).Abstract;
            p.transform.Find("Button").GetComponentInChildren<Text>().text = (x.Key==KeyCode.None)? "未设置按键":("按键: <color=#0028FF>"+x.Key.ToString()+"</color>");
            var tp = x;
            p.transform.GetComponentInChildren<Button>().onClick.SetListener(()=> { OnClickKeySettingButton(tp);AudioControl.Instance.PlaySound("Mouse"); }) ;
        }
    }
    void OnClickKeySettingButton(FuncField func)
    {
        UIManager.Instance.Open("KeyChangeUI",args: func);
    }
}